import { copyFile, mkdir, readdir, stat } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 数据库文件路径
const DB_PATH = join(__dirname, '../../database.sqlite');
const BACKUP_DIR = join(__dirname, '../../database/backups');

/**
 * 创建数据库备份
 */
export async function createBackup(): Promise<string> {
  try {
    // 确保备份目录存在
    await mkdir(BACKUP_DIR, { recursive: true });

    // 生成备份文件名（带时间戳）
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const backupFileName = `database-backup-${timestamp}.sqlite`;
    const backupPath = join(BACKUP_DIR, backupFileName);

    // 复制数据库文件
    await copyFile(DB_PATH, backupPath);

    console.log(`✅ 数据库备份成功: ${backupFileName}`);
    return backupPath;
  } catch (error) {
    console.error('❌ 数据库备份失败:', error);
    throw error;
  }
}

/**
 * 获取所有备份文件
 */
export async function listBackups(): Promise<Array<{ name: string; path: string; size: number; date: Date }>> {
  try {
    await mkdir(BACKUP_DIR, { recursive: true });
    
    const files = await readdir(BACKUP_DIR);
    const backups = [];

    for (const file of files) {
      if (file.endsWith('.sqlite')) {
        const filePath = join(BACKUP_DIR, file);
        const stats = await stat(filePath);
        
        backups.push({
          name: file,
          path: filePath,
          size: stats.size,
          date: stats.mtime
        });
      }
    }

    // 按日期排序（最新的在前）
    backups.sort((a, b) => b.date.getTime() - a.date.getTime());
    
    return backups;
  } catch (error) {
    console.error('❌ 获取备份列表失败:', error);
    return [];
  }
}

/**
 * 清理旧备份（保留最近的N个备份）
 */
export async function cleanupOldBackups(keepCount: number = 10): Promise<void> {
  try {
    const backups = await listBackups();
    
    if (backups.length <= keepCount) {
      console.log(`📁 当前备份数量: ${backups.length}，无需清理`);
      return;
    }

    const toDelete = backups.slice(keepCount);
    
    for (const backup of toDelete) {
      try {
        await import('fs/promises').then(fs => fs.unlink(backup.path));
        console.log(`🗑️  删除旧备份: ${backup.name}`);
      } catch (error) {
        console.error(`❌ 删除备份失败: ${backup.name}`, error);
      }
    }

    console.log(`✅ 清理完成，保留最近 ${keepCount} 个备份`);
  } catch (error) {
    console.error('❌ 清理旧备份失败:', error);
  }
}

/**
 * 自动备份任务
 */
export async function autoBackup(): Promise<void> {
  try {
    console.log('🔄 开始自动备份...');
    
    // 创建备份
    await createBackup();
    
    // 清理旧备份
    await cleanupOldBackups(10);
    
    console.log('✅ 自动备份完成');
  } catch (error) {
    console.error('❌ 自动备份失败:', error);
  }
}

// 如果直接运行此脚本，执行备份
if (import.meta.url === `file://${process.argv[1]}`) {
  autoBackup().catch(console.error);
}